import net.chrisrichardson.test.CommandResult
import net.chrisrichardson.test.MyStreamConsumer

abstract class CloudToolsBaseTests extends GroovyTestCase{
	
	def transactional = false
	
	protected static final String GRAILS_HOME = System.getenv("GRAILS_HOME")
	protected String grailsWorkDir
	
	void setUp(){
		grailsWorkDir = new File(System.getProperty("java.io.tmpdir"), "pluginTest" + System.currentTimeMillis()).getAbsolutePath();
		
		//create a phony application context or the deploy task won't run
		def file = new File("explodedWar/cloudtools/WEB-INF")
		file.mkdirs()
		new File(file, "applicationContext.xml").withWriter{}
	}
	
	protected def executeCommand(String command, String directory){
		Process process = Runtime.getRuntime().exec(command, null, new File("."))
		MyStreamConsumer inputStreamConsumer = new MyStreamConsumer(process.getInputStream())
		MyStreamConsumer errorStreamConsumer = new MyStreamConsumer(process.getErrorStream())
		new Thread(inputStreamConsumer).start()
		new Thread(errorStreamConsumer).start()
		
		int exitValue = process.waitFor()
		return new CommandResult(command, inputStreamConsumer.getText(), errorStreamConsumer.getText(), exitValue);
	}
	
	protected CommandResult executeGrailsCommand(String command, String directory) throws IOException, InterruptedException {
	    def grails = "grails"
		if(System.getProperty("os.name").contains("Windows")){ grails = "grails.bat" }
		return executeCommand(GRAILS_HOME +  "/bin/$grails -Dcloudtools.aws.properties=${System.getProperty('cloudtools.aws.properties')} " + "-Dgrails.work.dir=" + grailsWorkDir + " " + command, directory);
	}
	
	protected void assertStdOut(String expectedText, CommandResult result) {
	    if (result.getStdOut().indexOf(expectedText) < 0){
			fail(String.format("expected to find <%s> in %s", expectedText, result.getStdOut()));
		}
	}
	
	protected void assertStdErr(String expectedText, CommandResult result) {
	    if (result.getErrOut().indexOf(expectedText) < 0){
			fail(String.format("expected to find <%s> in %s", expectedText, result.getStdOut()));
		}
	}

        protected void assertExitValue(int expectedValue, CommandResult result) {
            if (expectedValue != result.getExitValue()) {
                fail("Expected a exit value of $expectedValue but got ${result.getExitValue()} when executing $result.command");
            }
        }
}